﻿using Donal.Xms.Common;
using Donal.Xms.Web.UI;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Text;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;

namespace Donal.Xms.Web.tools
{
    /// <summary>
    /// ExportExcel 的摘要说明
    /// </summary>
    public class ExportExcel : IHttpHandler, IRequiresSessionState
    {
        Dictionary<int, string> dic_error_update = new Dictionary<int, string>();

        public void ProcessRequest(HttpContext context)
        {
            //取得处事类型
            string action = DTRequest.GetQueryString("action");

            if (action.LastIndexOf("_") > 0)
            {
                action = action.Substring(0, action.LastIndexOf("_"));
            }

            switch (action)
            {
                case "exp_excle_data": // 信息导出
                    exp_excle_data(context);
                    break;
                case "imp_excle_data": // 信息导入
                    imp_excle_data(context);
                    break;
            }
        }



        #region  信息导出

        private void exp_excle_data(HttpContext context)
        {
            //检查用户是否登录
            Model.manager model = new ManagePage().GetAdminInfo();
            if (model == null)
            {
                context.Response.Write("{\"status\":0, \"msg\":\"对不起，用户尚未登录或已超时！\"}");
                return;
            }

            string action = DTRequest.GetFormString("action");
            string _keywords = DTRequest.GetFormString("keywords");
            string _property = "";
            string _start_time = "";
            string _end_time = "";

            StringBuilder strTemp = new StringBuilder();
            DataSet ds = new DataSet();
            DataTable temp = new DataTable();
            DataRow dataRow = temp.NewRow();

            switch (action)
            {
                case "users_export":
                    #region 员工模板导出
                    _keywords = DTRequest.GetFormString("keywords");
                    _property = DTRequest.GetFormString("property");
                    _start_time = DTRequest.GetFormString("start_time");
                    _end_time = DTRequest.GetFormString("end_time");

                    #region 组合SQL查询语句==========================

                    _keywords = _keywords.Replace("'", "");
                    _start_time = _start_time.Replace("'", "");
                    if (!string.IsNullOrEmpty(_start_time))
                    {
                        strTemp.Append(" and datediff(d,reg_time,'" + _start_time + "')<=0");
                    }
                    _end_time = _end_time.Replace("'", "");
                    if (!string.IsNullOrEmpty(_end_time))
                    {
                        strTemp.Append(" and datediff(d,reg_time,'" + _end_time + "')>=0");
                    }
                    _keywords = _keywords.Replace("'", "");
                    if (!string.IsNullOrEmpty(_keywords))
                    {
                        strTemp.Append(" and (user_name like '%" + _keywords
                            + "%' or mobile like '%" + _keywords
                            + "%' or email like '%" + _keywords
                            + "%' or nick_name like '%" + _keywords + "%')");
                    }
                    if (_property != "")
                    {
                        strTemp.Append(" and status =" + (Utils.StrToInt(_property, 0) - 1));
                    }

                    #endregion                                       

                    temp = new DataTable();
                    temp.Columns.Add("序号");
                    temp.Columns.Add("主键");
                    temp.Columns.Add("员工编号");
                    temp.Columns.Add("员工姓名");
                    temp.Columns.Add("身份证号");
                    temp.Columns.Add("组别");
                    temp.Columns.Add("状态");
                    temp.Columns.Add("生日");
                    temp.Columns.Add("性别");
                    temp.Columns.Add("手机");
                    temp.Columns.Add("邮箱");
                    temp.Columns.Add("QQ");
                    temp.Columns.Add("入职日期");
                    temp.Columns.Add("地址");

                    dataRow = temp.NewRow();

                    ds = new BLL.users().GetList(0, " id>0 " + strTemp.ToString(), "id");
                    if (Utils.CheckDataSet(ds))
                    {
                        BLL.user_groups ug = new BLL.user_groups();
                        int index = 1;

                        foreach (DataRow dr in ds.Tables[0].Rows)
                        {
                            dataRow = temp.NewRow();
                            dataRow["序号"] = index++;
                            dataRow["主键"] = dr["id"].ToString();
                            dataRow["员工编号"] = dr["user_name"].ToString();
                            dataRow["员工姓名"] = dr["nick_name"].ToString();
                            dataRow["身份证号"] = dr["msn"].ToString();
                            //dataRow["组别"] = ug.GetTitleAndParentTitle(Utils.StrToInt(dr["group_id"].ToString(), 0));
                            dataRow["状态"] = GetUserStatus(Utils.StrToInt(dr["status"].ToString(), 0));
                            dataRow["生日"] = Utils.ObjectToDateTime(dr["birthday"].ToString()).ToString("yyyy-MM-dd");
                            dataRow["性别"] = dr["sex"].ToString();
                            dataRow["手机"] = dr["mobile"].ToString();
                            dataRow["邮箱"] = dr["email"].ToString();
                            dataRow["QQ"] = dr["QQ"].ToString();
                            dataRow["入职日期"] = Utils.ObjectToDateTime(dr["reg_time"].ToString()).ToString("yyyy-MM-dd");
                            dataRow["地址"] = dr["address"].ToString();

                            temp.Rows.Add(dataRow);
                        }

                    }
                    else
                    {
                        dataRow = temp.NewRow();
                        dataRow["序号"] = 0;
                        dataRow["主键"] = "";
                        dataRow["员工编号"] = "";
                        dataRow["员工姓名"] = "";
                        dataRow["身份证号"] = "";
                        dataRow["组别"] = "";
                        dataRow["状态"] = "";
                        dataRow["生日"] = "";
                        dataRow["性别"] = "";
                        dataRow["手机"] = "";
                        dataRow["邮箱"] = "";
                        dataRow["QQ"] = "";
                        dataRow["入职日期"] = "";
                        dataRow["地址"] = "";

                        temp.Rows.Add(dataRow);
                    }

                    try
                    {
                        string urlPath = ExcelHelper.DataSetToExcel(temp, "员工数据", 6);

                        context.Response.Write("{\"status\":1, \"msg\":\"" + urlPath + "\"}");
                        return;
                    }
                    catch (Exception ex)
                    {
                        context.Response.Write("{\"status\":0, \"msg\":\"" + ex.Message + "\"}");
                        return;
                    }
                    #endregion
                    break;
            }

        }
        #endregion

        #region  信息导入

        private void imp_excle_data(HttpContext context)
        {
            //检查用户是否登录
            Model.manager model = new ManagePage().GetAdminInfo();
            if (model == null)
            {
                context.Response.Write("{\"status\":0, \"msg\":\"对不起，用户尚未登录或已超时！\"}");
                return;
            }

            string expath = DTRequest.GetFormString("expath");
            string action = DTRequest.GetFormString("action");

            if (expath.Trim() == "" || action.Trim() == "")
            {
                context.Response.Write("{\"status\":0, \"msg\":\"对不起，参数有误！\"}");
                return;
            }

            string path = Utils.GetMapPath(expath);

            try
            {
                DataTable dt = ExcelHelper.ExcelToDataTable(path, 3);

                //数据处理
                GetStandarData(dt, action);

                if (dt.Columns.Contains("errorMessage"))
                {
                    dt.Columns.Remove("errorMessage");
                }

                dt.Columns.Add("errorMessage");

                if (dic_error_update != null && dic_error_update.Count > 0)
                {
                    if (dic_error_update.ContainsKey(0))
                    {
                        context.Response.Write("{\"status\":0, \"msg\":\"" + dic_error_update[0] + "\"}");
                        return;
                    }

                    DataTable tempDt = dt.Clone();
                    foreach (DataRow dr in dt.Rows)
                    {
                        if (dic_error_update.ContainsKey(int.Parse(dr[0].ToString())))
                        {
                            dr["errorMessage"] = dic_error_update[int.Parse(dr[0].ToString())];
                            tempDt.Rows.Add(dr.ItemArray);
                        }
                    }

                    string errorName = string.Empty;
                    switch (action)
                    {
                        case "users_import":
                            errorName = "员工导入出错";
                            break;
                    }

                    string errorFilePath = ExcelHelper.DataSetToExcel(tempDt, errorName);

                    context.Response.Write("{\"status\":2, \"msg\":\"更新完成，但有错误！\", \"path\":\"" + errorFilePath + "\"}");
                    return;
                }
                else
                {
                    context.Response.Write("{\"status\":1, \"msg\":\"操作成功！\"}");
                    return;
                }
            }
            catch (Exception e)
            {
                context.Response.Write("{\"status\":0, \"msg\":\"" + e.Message + "\"}");
                return;
            }

        }
        #endregion

        #region 导入数据更新

        /// <summary>
        /// 导入数据
        /// </summary>
        /// <param name="dt">要导入的数据</param>
        /// <returns>未导入的数据</returns>
        private void GetStandarData(DataTable dt, string action)
        {
            //检查用户是否登录
            Model.manager model = new ManagePage().GetAdminInfo();

            int number = 0;

            switch (action)
            {
                case "users_import"://员工数据导入
                    #region 员工组别数据

                    DataTable _ugDt = new BLL.user_groups().GetList(0,"","").Tables[0];

                    if (!Utils.CheckDataTable(_ugDt))
                    {
                        set_dic_error(0, "没有找到员工组别！");
                        return;
                    }

                    #region 导入处理

                    BLL.users _users = new BLL.users();
                    Model.users users_model = new Model.users();
                    int _id = 0;

                    foreach (DataRow dr in dt.Rows)
                    {
                        number = Utils.StrToInt(dr["序号"].ToString(), 0);
                        _id = Utils.StrToInt(dr["主键"].ToString(), 0);
                        users_model = _users.GetModel(Math.Abs(Utils.StrToInt(dr["主键"].ToString(), 0)));

                        if (users_model == null)
                        {
                            users_model = new Model.users();
                        }
                        else
                        {
                            if (_id < 0)
                            {
                                _users.Delete(Math.Abs(_id));
                                continue;
                            }
                        }

                        int gid = 0;
                        int pid = 0;
                        string[] groupTitles = dr["组别"].ToString().Split(' ');
                        if (groupTitles.Length > 0)
                        {
                            foreach (string title in groupTitles)
                            {
                                gid = GetGroupId(_ugDt, title, pid);
                                if (gid > 0)
                                {
                                    pid = gid;
                                }
                            }
                        }
                        else
                        {
                            users_model.group_id = 0;
                            continue;
                        }

                        users_model.group_id = gid;
                        users_model.user_name = dr["员工编号"].ToString();
                        users_model.nick_name = dr["员工姓名"].ToString();
                        //users_model.msn = dr["身份证号"].ToString();
                        users_model.status = dr["状态"].ToString() == "正常" ? 0 : dr["状态"].ToString() == "休假" ? 1 : dr["状态"].ToString() == "禁用" ? 2 : 3;
                        users_model.birthday = Utils.ObjectToDateTime(dr["生日"]);
                        users_model.sex = dr["性别"].ToString();
                        users_model.mobile = dr["手机"].ToString();
                        users_model.email = dr["邮箱"].ToString();
                        users_model.qq = dr["QQ"].ToString();
                       // users_model.reg_time = Utils.ObjectToDateTime(dr["入职日期"]);
                        users_model.address = dr["地址"].ToString();


                        if (_id != 0)
                        {
                            if (!_users.Update(users_model))
                            {
                                set_dic_error(number, "更新时出错！");
                                continue;
                            }
                        }
                        else
                        {
                            _id = _users.Add(users_model);

                            if (_id == 0)
                            {
                                set_dic_error(number, "添加时出错！");
                                continue;
                            }
                        }
                    }
                    #endregion

                    #endregion
                    break;

            }

        }



        #endregion

        #region 辅助方法

        private void set_dic_error(int number, string msg)
        {
            if (number == 0)
            {
                dic_error_update = new Dictionary<int, string>();
                dic_error_update.Add(0, msg);
            }
            else
            {
                if (!dic_error_update.ContainsKey(number))
                {
                    dic_error_update.Add(number, msg);
                }
                else
                {
                    dic_error_update[number] += " " + msg;
                }
            }
        }

        #region 返回用户状态=============================
        private string GetUserStatus(int status)
        {
            string result = string.Empty;
            switch (status)
            {
                case 0:
                    result = "正常";
                    break;
                case 1:
                    result = "休假";
                    break;
                case 2:
                    result = "禁用";
                    break;
                case 3:
                    result = "离职";
                    break;
            }
            return result;
        }
        #endregion

        #region 返回组别ID

        private int GetGroupId(DataTable groupDt, string title, int parent_id)
        {
            int result = 0;

            if (Utils.CheckDataTable(groupDt))
            {
                DataRow[] drs = groupDt.Select("parent_id=" + parent_id + " and title = '" + title + "'");

                if (drs.Length > 0)
                {
                    result = Utils.ObjToInt(drs[0]["id"]);
                }
                else
                {
                    result = parent_id;
                }
            }

            return result;
        }

        #endregion

        #endregion

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}